package com.piece.core.rabbit.consumer;

import com.piece.core.framework.constant.RegisterConstants;
import com.piece.core.framework.support.dto.PayloadDTO;
import com.piece.core.framework.util.message.MessageFactory;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

@Slf4j
@RabbitListener(queues = RegisterConstants.QUEUE_NAME, containerFactory = "singleListenerContainer")
public class RabbitMessageConsumer {

    private MessageFactory messageFactory;

    public RabbitMessageConsumer(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

    @RabbitHandler
    public void handleMessageReceive(PayloadDTO payload, Message message, Channel channel) throws Exception {
        try {
            messageFactory.getOperator(payload.getOperator()).doReceive(payload);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 手动删除消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            // 消息重新放回队列
            // messageFactory.get().reSend(payload);
        }
    }
}
